package com.gitee.fanx.retty.web;

import io.netty.handler.codec.http.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fanhang
 */
public class RouteMapping {

	private Logger log = LoggerFactory.getLogger(RouteMapping.class);

	private Map<HttpMethod, Map<String, Route>> typesRouteMap;

	public RouteMapping() {
		this.typesRouteMap = new HashMap<>(5);
		this.typesRouteMap.put(HttpMethod.GET, new HashMap<>(32));
		this.typesRouteMap.put(HttpMethod.POST, new HashMap<>(32));
		this.typesRouteMap.put(HttpMethod.PUT, new HashMap<>(32));
		this.typesRouteMap.put(HttpMethod.DELETE, new HashMap<>(32));
		this.typesRouteMap.put(HttpMethod.PATCH, new HashMap<>(32));
	}

	public void add(HttpMethod httpMethod, String path, Route route) {
		this.typesRouteMap.get(httpMethod).put(path, route);
		log.info("mapping [{} {}] -> {}", httpMethod.name(), path, route);
	}

	public void get(String path, Route route) {
		this.add(HttpMethod.GET, path, route);
	}

	public void post(String path, Route route) {
		this.add(HttpMethod.POST, path, route);
	}

	public void put(String path, Route route) {
		this.add(HttpMethod.PUT, path, route);
	}

	public void delete(String path, Route route) {
		this.add(HttpMethod.DELETE, path, route);
	}

	public void patch(String path, Route route) {
		this.add(HttpMethod.PATCH, path, route);
	}

	public Route match(HttpMethod httpMethod, String path) {
		Map<String, Route> routeMap = this.typesRouteMap.get(httpMethod);
		if (routeMap != null && !routeMap.isEmpty()) {
			return routeMap.get(path);
		}
		return null;
	}
}
